# %%
import time
import requests
import json
import fake_useragent
import os
os.environ['PYGAME_HIDE_SUPPORT_PROMPT'] = '1'
import pygame
# %%
os.chdir(os.path.dirname(os.path.abspath(__file__)))
url = 'https://api.forchange.cn/'
headers = {'User-Agent': fake_useragent.UserAgent().random,
           'Content-Type': 'application/json',
           'Accept': 'application/json, text/plain, */*',
           'Accept-Encoding': 'gzip, deflate, br',
           'Accept-Language': 'zh-CN,zh;q=0.9,en;q=0.8',
           'Connection': 'keep-alive',
           'Host': 'api.forchange.cn',
           'Origin': 'https://www.forchange.cn',
           'Referer': 'https://www.forchange.cn/',
           'Sec-Fetch-Dest': 'empty',
           'Sec-Fetch-Mode': 'cors',
           'Sec-Fetch-Site': 'same-site',
           'X-Requested-With': 'XMLHttpRequest'}

# %%
def get_answer(question,prefix=''):
    """This function calls the ForChange API and returns an answer

    Parameters:
    question (string): The question you would like to ask

    Returns:
    answer (string): The answer to the question
    """
    if prefix:
        prefix = f'（{prefix}）'
    data = {'prompt': f'下面是截取自西藏自治区林芝市察隅县政府报告中的一段话，请找这出段话中的错别字{prefix}：\n{question}' }
    try:
        res = requests.post(url, headers=headers, data=json.dumps(data))
        out = res.json()['choices'][0]['text']
        if '非常抱歉，根据我们的产品规则，无法为你提供该问题的回答，请尝试其他问题' in out:
            return None
    except KeyboardInterrupt:
        exit(0)
    except:
        return None
    return out

#%%
import docx
import re

def look_at_this_passage(filename:str):
    fix_pat = re.compile('(\w+)\s*→\s*(\w+)')
    doc = docx.Document(filename)
    print(f'File: {filename}\n Length: {len(doc.paragraphs)}')
    for i, para in enumerate(doc.paragraphs):
        
        if not para.text.strip():continue
        text = para.text if not para.text.endswith('\n') else para.text[:-1]
        text = text.strip()
        assert not text.endswith('\n')
        if len(text)<20:
            print(f'[-{i}]{text}')
            continue
        answer = get_answer(text)
        if answer is None:
            print(f'[-{i}]{text}')
            continue
        answer = answer.strip()
        if '没有错别字' in answer or '无错别字' in answer or answer.strip() =='没有':
            print(f'[P{i}]{text}')
            continue
        misspells = re.findall(fix_pat, answer)
        if misspells:
            misspells = misspells[0]
            if misspells[0] == misspells[1]:
                print(f'[-{i}]{text}')
                continue
            text = text.replace(misspells[0], f'\x1b[33m{misspells[0]}\x1b[0m')
        print(f'[{i}]{text}\n\x1b[31m{answer}\x1b[0m')

if __name__ == '__main__':
    import sys
    if len(sys.argv) > 1:
        look_at_this_passage(sys.argv[1])
    else:
        print('doc-check.py <filename>')
